<script lang="ts" setup>
import type {
  InventoryDetail,
  Location,
  MoveInventoryParams,
  Warehouse,
} from '../types';

import { ref } from 'vue';

import { BasicModal, useVbenModal } from '@vben/uikit';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { $t } from '#/locales';

import { useMoveFormSchema } from '../data';
import { getLocationList, getWarehouseList, moveInventory } from '../services';

const emit = defineEmits(['success']);
const formData = ref<MoveInventoryParams>();
const [Modal, modalApi] = useVbenModal({
  title: $t('inventory.moveModal.title'),
  fullscreenButton: false,
  showOkButton: true,
  showCancelButton: true,
  onConfirm: handleSubmit,
});

// 导出组件名称，与导入保持一致
defineExpose({
  name: 'InventoryMoveModal',
  openModal: (data: InventoryDetail) => {
    modalApi.setData(data);
    modalApi.open();
  }
});

const loading = ref(false);
const warehouseList = ref<Warehouse[]>([]);
const locationList = ref<Location[]>([]);

const defaultFormData: MoveInventoryParams = {
  inventory_id: '',
  product_code: '',
  product_name: '',
  specification: '',
  unit: '',
  current_quantity: 0,
  from_warehouse: '',
  to_warehouse: '',
  from_location: '',
  to_location: '',
  move_quantity: 0,
  reason: '',
  remark: '',
};

// 表单配置
const formSchema = useMoveFormSchema(warehouseList, locationList);

/**
 * 表单实例
 */
const [Form, formApi] = useVbenForm({
  schema: formSchema,
  rules: {
    from_warehouse: [
      {
        required: true,
        message: $t('inventory.moveModal.fromWarehouseRequired'),
      },
    ],
    to_warehouse: [
      {
        required: true,
        message: $t('inventory.moveModal.toWarehouseRequired'),
      },
      {
        validator(_, value) {
          if (value === formData.value?.from_warehouse) {
            return new Error($t('inventory.moveModal.diffWarehouseRequired'));
          }
          return Promise.resolve();
        },
      },
    ],
    from_location: [
      {
        required: true,
        message: $t('inventory.moveModal.fromLocationRequired'),
      },
    ],
    to_location: [
      { required: true, message: $t('inventory.moveModal.toLocationRequired') },
      {
        validator(_, value) {
          if (
            value === formData.value?.from_location &&
            formData.value?.from_warehouse === formData.value?.to_warehouse
          ) {
            return new Error($t('inventory.moveModal.diffLocationRequired'));
          }
          return Promise.resolve();
        },
      },
    ],
    move_quantity: [
      { required: true, message: $t('inventory.moveModal.quantityRequired') },
      {
        validator(_, value) {
          if (!value || value <= 0) {
            return new Error($t('inventory.moveModal.quantityPositive'));
          }
          return Promise.resolve();
        },
      },
      {
        validator(_, value) {
          if (value > (formData.value?.current_quantity || 0)) {
            return new Error($t('inventory.moveModal.quantityExceed'));
          }
          return Promise.resolve();
        },
      },
    ],
    reason: [
      { required: true, message: $t('inventory.moveModal.reasonRequired') },
    ],
  },
  layout: 'vertical',
});

/**
 * 加载仓库列表
 */
async function loadWarehouseList() {
  try {
    // 使用无参数的getWarehouseList以匹配services.ts中的实现
    const res = await getWarehouseList();
    warehouseList.value = res || [];
  } catch (error) {
    message.error($t('inventory.moveModal.warehouseListFailed'));
    warehouseList.value = [];
  }
}

/**
 * 加载库位列表
 * @param warehouseId - 仓库ID
 */
async function loadLocationList(warehouseId: string) {
  try {
    // 使用单个参数的getLocationList以匹配services.ts中的实现
    const res = await getLocationList(Number(warehouseId));
    return res || [];
  } catch (error) {
    message.error($t('inventory.moveModal.locationListFailed'));
    return [];
  }
}

/**
 * 提交表单
 */
async function handleSubmit() {
  try {
    loading.value = true;
    // 表单校验
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }

    // 获取表单值
    const values = await formApi.getValues();

    // 调用API提交数据
    const moveData = {
      inventory_id: formData.value?.inventory_id || '',
      from_warehouse: values.from_warehouse,
      from_location: values.from_location,
      to_warehouse: values.to_warehouse,
      to_location: values.to_location,
      move_quantity: values.move_quantity,
      reason: values.reason,
      remark: values.remark,
    };
    await moveInventory(moveData);

    // 关闭模态框
    modalApi.close();

    // 触发成功事件
    emit('success');
  } catch (error) {
    message.error(error?.message || $t('inventory.moveModal.failed'));
  } finally {
    loading.value = false;
  }
}

// 监听模态框打开事件
modalApi.onOpenChange(async (isOpen) => {
    if (isOpen) {
      const data = modalApi.getData<InventoryDetail>();
      if (data) {
        // 设置表单数据
        const moveData: MoveInventoryParams = {
          inventory_id: data.inventory_id || '',
          product_code: data.product_code || '',
          product_name: data.product_name || '',
          specification: data.specification || '',
          unit: data.unit || '',
          current_quantity: data.quantity || 0,
          from_warehouse: data.warehouse || '',
          to_warehouse: '',
          from_location: data.location || '',
          to_location: '',
          move_quantity: 0,
          reason: '',
          remark: '',
        };

        formData.value = moveData;
        formApi.setValues(moveData);

        // 加载仓库列表
        await loadWarehouseList();

        // 如果有源仓库ID，加载源库位列表
        if (data.warehouse) {
          const fromLocations = await loadLocationList(String(data.warehouse));
          formApi.setPropsByFieldName('from_location', {
            options: fromLocations.map((item) => ({
              label: item.location_name,
              value: item.location_id,
            })),
          });
        }
      }
    }
  });
</script>

<template>
  <BasicModal
    :title="$t('inventory.moveModal.title')"
    :confirm-loading="loading"
    :width="700"
    @ok="handleSubmit"
  >
    <Form />
  </BasicModal>
</template>
